package edu.ucla.wanda.social;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

public class FacebookAppAdapter {
	private String appId;
	private HashMap<String, String> attrs;

	public FacebookAppAdapter(String appId) throws IOException {
		attrs = new HashMap<String, String>(20);
		this.appId = appId;
		
		refresh();
	}
	
	public void refresh() throws IOException
	{
		attrs.clear();
		
		URL url = null;

		try {
			url = new URL("https://graph.facebook.com/" + appId);
		} catch (MalformedURLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		HttpURLConnection cxn = (HttpURLConnection) url.openConnection();

		cxn.setRequestMethod("GET");
		cxn.setRequestProperty("Accept", "application/json");

		JsonObject o = new JsonParser().parse(new InputStreamReader(cxn.getInputStream())).getAsJsonObject();
		
		for(Map.Entry<String, JsonElement> m : o.entrySet())
		{	
			if(!m.getValue().isJsonPrimitive())
			{
				continue;
			}
			
			String key = m.getKey();
			String val = m.getValue().getAsString();
			
			// stupid hack to get around Facebook feed restrictions
			if("logo_url".equals(key))
			{
				val = "http://fbcdn-photos-a.akamaihd.net/photos-ak-snc1/v85006/167/321155711249351/app_1_321155711249351_6799.gif";
			}
			
			else if("icon_url".equals(key))
			{
				val = "http://fbcdn-photos-a.akamaihd.net/photos-ak-snc1/v85006/167/321155711249351/app_2_321155711249351_6821.gif";
			}
			
			attrs.put(key, val);
		}
	}
	
	public String getValue(String key)
	{
		return attrs.get(key);
	}

	public List<Map.Entry<String, String>> getValues()
	{
		return new ArrayList<Map.Entry<String, String>>(attrs.entrySet());
	}
}
